package com.atrix.CinemaView.controller;

import com.atrix.CinemaView.pojo.dto.info.VideoInfo;
import com.atrix.CinemaView.pojo.dto.VideoStreamData;
import com.atrix.CinemaView.pojo.vo.R;
import com.atrix.CinemaView.service.VideoService;
import com.atrix.CinemaView.utils.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/api/video")
@Api("视频控制器")
public class VideoController {
    @Autowired
    VideoService videoService;
    
    @GetMapping("/{containerIndex}/{index}")
    @ApiOperation("根据索引获取视频")
    public void getVideo(@ApiParam("视频容器索引") @PathVariable("containerIndex") Integer containerIndex,
                         @ApiParam("容器内视频索引") @PathVariable("index") Integer index,
                         HttpServletRequest request,
                         HttpServletResponse response) {
        VideoStreamData video = videoService.getVideo(containerIndex, index);
        long skip = processSkipAndSetResponse(video, request, response);
        FileUtil.outputFile(video, response, skip);
    }
    
    @GetMapping("/info")
    @ApiOperation("获取所有视频信息")
    public R<List<VideoInfo>> getVideoInfo() {
        return R.<List<VideoInfo>>success().setData(videoService.getVideoInfo());
    }
    
    @GetMapping("/title/{containerIndex}/{index}")
    @ApiOperation("根据索引，获取视频标题（文件名）")
    public R<String> getVideoTitle(@ApiParam("容器索引") @PathVariable("containerIndex") Integer containerIndex,
                                 @ApiParam("容器内视频索引") @PathVariable("index") Integer index) {
        List<VideoInfo> videoInfo = videoService.getVideoInfo();
        return R.<String>success().setData(
                videoInfo.get(containerIndex)
                        .getVideoNameList()
                        .get(index)
        );
    }
    
    /**
     * 处理视频跳转并将视频输出到前端
     * @return 视频需要跳过的字节长度
     */
    private long processSkipAndSetResponse(VideoStreamData video,
                                           HttpServletRequest request,
                                           HttpServletResponse response) {
        long fileSize = video.getSize();
        String rangeHeader = request.getHeader("Range");
        response.setContentLengthLong(fileSize);
        response.setContentType("video/" + video.getType());
        if (rangeHeader != null && rangeHeader.startsWith("bytes=")) {
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            String range = rangeHeader.substring("bytes=".length());
            long start = Long.parseLong(range.split("-")[0]);
            long end = range.split("-").length > 1 ? Long.parseLong(range.split("-")[1]) : fileSize - 1;
            response.setHeader("Content-Range", "bytes " + start + "-" + end + "/" + fileSize);
            response.setContentLengthLong(end - start + 1);
            return start;
        }
        return 0;
    }
}
